<template>
  <div v-loading="loading">
    <create-sections
      title="月度目标"
      class="wk-base-detail__section"
      content-height="auto">
      <el-table
        v-loading="loading"
        id="summary-table"
        :row-height="40"
        :data="summaryList"
        use-virtual
        class="n-table--border el-table-header--white"
        stripe
        height="100"
        border
        highlight-current-row
        style="width: 100%">
        <el-table-column
          v-for="(item, index) in summaryFields"
          :key="index"
          :prop="item.fieldName"
          :label="item.name"
          :min-width="item.width ? item.width : ''"
          :formatter="summaryFieldFormatter"
          align="center"
          show-overflow-tooltip/>
        <el-table-column
          v-if="status == 1 && reportBrandTargetAuth"
          label="操作"
          fixed="right"
          width="100">
          <template slot-scope="scope">
            <el-dropdown
              trigger="click"
              @command="commandSelect($event, 'summary', scope.row)">
              <i class="el-icon-more table-more" style="cursor: pointer" />
              <el-dropdown-menu slot="dropdown" style="width: 150px;">
                <el-dropdown-item
                  v-for="(item, index) in summaryDropdownItems"
                  :key="index"
                  :icon="item.icon"
                  :command="item.command">{{ item.label }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </create-sections>
    <create-sections
      title="品牌汇总"
      class="wk-base-detail__section"
      content-height="auto">
      <el-table
        v-loading="loading"
        id="brand-table"
        :row-height="40"
        :data="brandList"
        use-virtual
        class="n-table--border el-table-header--white"
        stripe
        height="300"
        border
        highlight-current-row
        style="width: 100%">
        <el-table-column
          v-for="(item, index) in brandFields"
          :key="index"
          :prop="item.fieldName"
          :label="item.name"
          :min-width="item.width ? item.width : ''"
          :formatter="brandFieldFormatter"
          align="center"
          show-overflow-tooltip/>
        <el-table-column
          v-if="status == 1 && reportBrandTargetAuth"
          label="操作"
          fixed="right"
          width="100">
          <template slot-scope="scope">
            <el-dropdown
              trigger="click"
              @command="commandSelect($event, 'brand', scope.row)">
              <i class="el-icon-more table-more" style="cursor: pointer" />
              <el-dropdown-menu slot="dropdown" style="width: 150px;">
                <el-dropdown-item
                  v-for="(item, index) in brandDropdownItems"
                  :key="index"
                  :icon="item.icon"
                  :command="item.command">{{ item.label }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="status == 1 && reportBrandTargetAuth" slot="header" class="wk-base-detail__more" style="text-align: right; width: 100%;">
        <el-button type="primary" icon="el-icon-plus" circle @click="commandSelect('add', 'brand')" />
      </div>
    </create-sections>

    <form-add-dialog
      ref="formAdddialog"
      :title="formAddTitle"
      :form.sync="formAddForm"
      :rules="formAddRules"
      :fields="formAddFields"
      :visible.sync="formAddDialogShow"
      @pass="uploadEmployeeRelativeData"
    />
  </div>
</template>

<script>
import {
  reportBrandListQueryAPI,
  reportBrandAddOrUpdateAPI,
  reportBrandDeleteAPI
} from '@/api/oa/reportBrand'
import {
  reportSummaryListQueryAPI,
  reportSummaryAddOrUpdateAPI,
  reportSummaryDeleteAPI
} from '@/api/oa/reportSummary'

import CreateSections from '@/components/CreateSections'
import FormAddDialog from './FormAddDialog'

import {
  brandModel,
  summaryModel,
  timeUnitOption,
  summaryDataFieldOptions,
  storeNameOptions
} from '../model/report'
import { objDeepCopy } from '../../../../utils'
import { mapGetters } from 'vuex'

export default {
  name: 'ReportBrandInfo',
  components: {
    CreateSections,
    FormAddDialog
  },
  props: {
    id: [String, Number],
    status: [String, Number]
  },
  data() {
    return {
      loading: false,
      summaryList: [],
      summaryFields: [],
      brandList: [],
      brandFields: [],
      // 弹窗添加
      formAddTitle: '',
      formAddForm: {},
      formAddRules: {},
      formAddFields: [],
      formAddDialogShow: false,
      // 标识修改的是什么数据
      updateType: '',
      brandDropdownItems: [{
        label: '编辑',
        command: 'update',
        icon: 'wk wk-icon-modify'
      }, {
        label: '删除',
        command: 'delete',
        icon: 'wk wk-delete'
      }],
      summaryDropdownItems: [{
        label: '编辑',
        command: 'update',
        icon: 'wk wk-icon-modify'
      }
      // {
      //   label: '删除',
      //   command: 'delete',
      //   icon: 'wk wk-delete'
      // }
      ]
    }
  },

  computed: {
    ...mapGetters([
      'reportBrandTargetAuth'
    ])
  },
  watch: {
    id: {
      handler() {
        this.getDetail()
      },
      immediate: true
    }
  },
  mounted() {
  },

  beforeDestroy() {
    this.updateType = ''
  },
  methods: {
    /**
     * 获取基础信息
     */
    getDetail() {
      this.loading = true
      reportSummaryListQueryAPI(this.id, 1)
        .then(res => {
          this.loading = false
          const data = res.data || []
          this.summaryList = data
          this.summaryFields = this.getCommonFieldListValue('summary')
        }).catch(() => {
          this.loading = false
        })
      reportBrandListQueryAPI(this.id)
        .then(res => {
          const data = res.data || []
          this.brandList = data
          this.brandFields = this.getCommonFieldListValue('brand')
        }).catch(() => {})
    },

    /**
     *常规字段值
     */
    getCommonFieldListValue(type) {
      const list = []
      if (type == 'summary') {
        summaryModel.field.forEach(item => {
          const temp = {}
          temp.fieldName = item.field
          temp.name = item.name
          list.push(temp)
        })
      } else if (type == 'brand') {
        brandModel.field.forEach(item => {
          const temp = {}
          temp.fieldName = item.field
          temp.name = item.label
          list.push(temp)
        })
      }
      return list
    },

    /**
     * 格式化字段
     */
    brandFieldFormatter(row, column) {
      if (column.property == 'period') {
        return timeUnitOption.find(item => item.value == row[column.property]).label || '--'
      } else if (column.property == 'storeType') {
        return storeNameOptions.find(item => item.value == row[column.property]).label || '--'
      } else if (column.property == 'refundRate') {
        return row[column.property] ? row[column.property] + '%' : '0%'
      } else {
        return row[column.property] == null ? 0 : row[column.property]
      }
    },

    /**
     * 格式化字段
     */
    summaryFieldFormatter(row, column) {
      if (column.property == 'period') {
        return timeUnitOption.find(item => item.value == row[column.property]).label || '--'
      } else if (column.property == 'dataField') {
        return summaryDataFieldOptions.find(item => item.value == row[column.property]).label || '--'
      } else if (column.property == 'completeNow') {
        return row.actual + row.complete
      } else if (column.property == 'completeProgress') {
        return row[column.property] ? row[column.property] + '%' : '0%'
      } else {
        return row[column.property] == null ? 0 : row[column.property]
      }
    },

    /**
     * 提交数据
     */
    uploadEmployeeRelativeData() {
      const param = objDeepCopy(this.formAddForm)
      param.reportId = this.id
      if (this.updateType == 'summary') {
        reportSummaryAddOrUpdateAPI(param).then(res => {
          this.$message.success(`${this.formAddTitle}成功`)
          this.formAddDialogShow = false
          this.getDetail()
        }).catch(() => {
          this.formAddDialogShow = false
        })
      } else if (this.updateType == 'brand') {
        param.reportSummaryId = this.summaryList[0].id
        reportBrandAddOrUpdateAPI(param).then(res => {
          this.$message.success(`${this.formAddTitle}成功`)
          this.formAddDialogShow = false
          this.getDetail()
        }).catch(() => {
          this.formAddDialogShow = false
        })
      }
    },

    /**
     * 编辑删除操作
     */
    commandSelect(command, type, data) {
      this.updateType = type
      if (command == 'delete') {
        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.updateType == 'summary') {
            reportSummaryDeleteAPI(data.id).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getDetail()
            }).catch(() => {})
          } else if (this.updateType == 'brand') {
            reportBrandDeleteAPI(data.id).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getDetail()
            }).catch(() => {})
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      } else if (command == 'update') {
        this.formAddForm = objDeepCopy(data)
        if (this.updateType == 'summary') {
          this.formAddTitle = '编辑月度目标'
          this.formAddRules = summaryModel.rule
          this.formAddFields = summaryModel.field
          this.formAddFields.forEach(item => {
            if (item.field == 'completeNow' || item.field == 'completeProgress') {
              item.disabled = true
            }
          })
          this.formAddDialogShow = true
        } else if (this.updateType == 'brand') {
          this.formAddTitle = '编辑品牌汇总'
          this.formAddRules = brandModel.rule
          this.formAddFields = brandModel.field
          this.formAddFields.forEach(item => {
            item.name = item.label
          })
          this.formAddDialogShow = true
        }
      } else if (command == 'add') {
        if (this.updateType == 'brand') {
          this.formAddTitle = '新增品牌汇总'
          this.formAddRules = brandModel.rule
          this.formAddFields = objDeepCopy(brandModel.field)
          this.formAddFields.forEach(item => {
            item.name = item.label
          })
          this.formAddForm = brandModel.form
          this.formAddDialogShow = true
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.base-add-button {
  width: 100%;
  margin: 10px 0;
  padding: 11px 12px;
}

.wk-base-detail-section + .wk-base-detail-section {
  border-top: 1px solid $xr-border-color-base;
}

.create-sections {
  /deep/ .create-sections-content {
    padding: 0 20px;
  }
}

.contract-files {
  width: 80%;
  margin: 20px 0 20px 10px;
}
</style>
